import { ref } from "vue";
import { Notify, Dialog } from "vant";
import { useMapConfig } from "@/hooks/map/useMapConfig.js";
import { useMapApi } from "@/utils/useMapApi";
import { getSysConfig } from "@/api/my/face.js";

// 获取位置
function useMap() {
  let popupShow = ref(false);
  let mapDom = ref(null);
  let radius = ref(0);
  let lng = ref(0);
  let lat = ref(0);
  let currentLng = ref(0);
  let currentLat = ref(0);
  let locationLoading = ref(false);
  let mapTimer = null;

  // 获取签到配置
  async function getSignConfig() {
    const res = await getSysConfig();
    console.log(res);
    if (res.data.code === 400) {
      Notify({ type: "warning", duration: 1000, message: res.data.message });
      return;
    }
    initMap();
    lng.value = res.data.data.lng;
    lat.value = res.data.data.lat;
    radius.value = res.data.data.radius;
  }

  // 初始化地图
  async function initMap() {
    await useMapApi();
    getLocation();
  }

  // 获取签到位置
  function getLocation() {
    window.AMap.plugin("AMap.Geolocation", function () {
      var geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 10000, //超过10秒后停止定位，默认：5s
        position: "RB", //定位按钮的停靠位置
        offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
        zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
      });
      // map.addControl(geolocation)
      geolocation.getCurrentPosition(function (status, result) {
        if (status == "complete") {
          onComplete(result);
        } else {
          onError(result);
        }
      });
    });
    //解析定位结果
    function onComplete(data) {
      console.log(data);
      if (data.info !== "SUCCESS") return;
      const requestOptions = {
        method: "GET",
        redirect: "follow",
      };
      fetch(
        `https://restapi.amap.com/v3/assistant/coordinate/convert?locations=${data.position.lng},${data.position.lat}&coordsys=gps&output=JSON&key=3336ce742313f21ed5e7c8787f4033bc`,
        requestOptions
      )
        .then(async (res) => {
          const resdata = await res.json();

          const lng = resdata.locations.split(",")[0];
          const lat = resdata.locations.split(",")[1];
          currentLng.value = lng;
          currentLat.value = lat;

          console.log(currentLng.value, currentLat.value, "经纬度");

          locationLoading.value = true;

          // let message = `
          //   location_type: ${data.location_type},
          //   lng: ${currentLng.value},
          //   lat: ${currentLat.value},
          //   isConverted: ${data.isConverted},
          // `;
          // Dialog.alert({
          //   title: "警告",
          //   message: message,
          // }).then(() => {
          //   Dialog.close();
          // });
        })
        .catch((error) => {
          console.log(error);
          Dialog.alert({
            title: "警告",
            message: "精确位置获取失败！",
          }).then(() => {
            Dialog.close();
          });
        });
    }
    //解析定位错误信息
    function onError(data) {
      if (data.status == "error") {
        //定位失败
        if (data.info == "NOT_SUPPORTED") {
          Notify({
            type: "warning",
            duration: 1000,
            message: "当前浏览器不支持定位功能",
          });
          return false;
        }
      }
      if (data.message.indexOf("Geolocation permission denied." !== -1)) {
        Notify({
          type: "warning",
          duration: 1000,
          message: "未给予app获取位置权限，无法获取当前位置",
        });
        return;
      }
    }
  }

  // 打开地图
  function openMap() {
    if (!locationLoading.value) return;
    popupShow.value = true;
    mapTimer = setTimeout(() => {
      useMapConfig(mapDom, lng, lat, radius, currentLng, currentLat);
    });
  }

  return {
    getSignConfig,
    openMap,
    currentLng,
    currentLat,
    mapTimer,
    popupShow,
    mapDom,
    locationLoading,
  };
}

export default useMap;
